package com.app.couponsharelife.ui.main.seeding

import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.BoutiqueData
import com.app.couponsharelife.data.bean.BoutiqueDataBean
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.ui.listener.MyMultiPurposeListener
import com.app.couponsharelife.ui.main.home.topic.TopicHDKActivity
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.boutique_commodity_rvitem.view.*
import kotlinx.android.synthetic.main.fragment_boutique_commodity.*
import java.text.SimpleDateFormat
import java.util.*

/**
 *Created by xct on 2019/5/7
 *Description:精品专场
 */
class BoutiqueFragment:LazyFragment() {
    private var dataList= arrayListOf<BoutiqueData>()
    private var pageIndex=1
    private var adapter:MyAdapter?=null
    private val simpleDateFormat = SimpleDateFormat("MM/dd", Locale.getDefault())
    companion object {
        fun newInstance(): BoutiqueFragment {
            val fragment = BoutiqueFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_boutique_commodity

    override fun initViews() {
        setRefresh()
        boutiqueCommodity_rv.layoutManager= LinearLayoutManager(context)
        adapter=MyAdapter()
        boutiqueCommodity_rv.adapter=adapter
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        boutiqueCommodity_smart.setEnableNestedScroll(true)
        boutiqueCommodity_smart.setOnMultiPurposeListener(object : MyMultiPurposeListener {
            override fun headerReleased() {
                animationDrawable.start()
            }

            override fun headerMoving(percent: Float) {
                setAnima(percent)
            }

            override fun headerFinish() {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }

            override fun loadMore() {
                getData(false)
            }

            override fun refresh() {
                //pageIndex=1
                getData(true)
            }

        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    override fun lazyLoad() {
        getData(false)
    }
    private fun getData(isRefresh:Boolean){
        showProgressDialog("加载中...")
        val map= HashMap<String,String>()
        RetrofitWorker.retrofitWorker.getSupSpecialTheme(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<BoutiqueDataBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<BoutiqueDataBean>) {
                        dismissProgressDialog()
                        if (isRefresh){
                            boutiqueCommodity_smart.finishRefresh()
                        }
                        if (it.code==200&&it.data!=null&&it.data!!.data!=null){
                            if (it.data!!.data!!.isNotEmpty()){
                                boutiqueCommodity_llerror.visibility=View.GONE
                                boutiqueCommodity_rv.visibility=View.VISIBLE
                                dataList.clear()
                                dataList.addAll(it.data!!.data!!)
                                boutiqueCommodity_smart.finishLoadMoreWithNoMoreData()
                                adapter!!.notifyDataSetChanged()
                            }else{
                                boutiqueCommodity_llerror.visibility=View.VISIBLE
                                boutiqueCommodity_rv.visibility=View.GONE
                            }
                        }else{
                            boutiqueCommodity_llerror.visibility=View.VISIBLE
                            boutiqueCommodity_rv.visibility=View.GONE
                        }
                    }

                    override fun onError(e: Throwable) {
                        dismissProgressDialog()
                        boutiqueCommodity_llerror.visibility=View.VISIBLE
                        boutiqueCommodity_rv.visibility=View.GONE
                        if (isRefresh){
                            boutiqueCommodity_smart.finishRefresh()
                        }
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }

                })
    }
    private inner class MyAdapter: RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.boutique_commodity_rvitem,parent,false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (dataList.isNotEmpty()) {
                if (holder is MyHolder) {
                    val boutiqueDataBean=dataList[position]
                    val imagUrl="http://img.haodanku.com/"+boutiqueDataBean.cms_image
                    Glide.with(activity!!).asBitmap()
                            .apply(RequestOptions().error(R.drawable.ic_app_place_holder3))
                            .load(imagUrl)
                            .into(holder.imagview!!)
                    var title=boutiqueDataBean.content?:""
                    if (title.contains("\n")){
                        title=title.replace("\n","")
                    }
                    holder.tvName!!.text=boutiqueDataBean.name?:""
                    holder.tvTitle!!.text=title
                    if (boutiqueDataBean.activity_start_time!=null&&boutiqueDataBean.activity_start_time!!.isNotEmpty()){
                        val startTime=simpleDateFormat.format(boutiqueDataBean.activity_start_time!!.toLong()*1000)
                        val endTime=simpleDateFormat.format(boutiqueDataBean.activity_end_time!!.toLong()*1000)
                        holder.tvTime!!.visibility=View.VISIBLE
                        holder.tvTime!!.text="活动时间 $startTime-$endTime"
                    }else{
                        holder.tvTime!!.visibility=View.GONE
                    }
                    holder.itemView.setOnClickListener {
                        val intent = Intent(context, TopicHDKActivity::class.java)
                        intent.putExtra("FavoritesID", boutiqueDataBean.id?:"")
                        intent.putExtra("ImagUrl",imagUrl)
                        intent.putExtra("Name", "精选专场")
                        startActivity(intent)
                    }
                }
            }
        }
    }
    private inner class MyHolder(itemview: View): RecyclerView.ViewHolder(itemview){
        var imagview:ImageView?=null
        var tvTime:TextView?=null
        var tvName:TextView?=null
        var tvTitle:TextView?=null
        init {
            imagview=itemview.ivGoods
            tvTime=itemview.tvTime
            tvName=itemview.tvName
            tvTitle=itemview.tvTitle
        }
    }
}